package shttps

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	sorts "main.go/sort"
	"net/http"
	"strings"
)

//响应参数
//响应参数
type Response struct {
	*http.Response             //原数据
	code           int         //状态码
	header         http.Header //请求头
	headers        []string    //请求头列表
	body           []byte      //返回内容
	err            error       //错误
}

func newResponseErr(err error) Response {
	return Response{err: err}
}

func newResponse(r *http.Response) Response {
	data := Response{Response: r}
	if r != nil {
		data.code = r.StatusCode
		data.header = r.Header
		body, err := ioutil.ReadAll(r.Body)
		if err != nil && data.err == nil {
			data.err = err
		}
		data.body = body
		for i, v := range data.header {
			data.headers = append(data.headers, fmt.Sprintln(i, ":", strings.Join(v, ",")))
		}
		sorts.SortString(data.headers)
	}
	return data
}

func (this Response) Body() []byte {
	return this.body
}

func (this Response) BodyString() string {
	return string(this.body)
}

func (this Response) BodyMap() (m map[string]interface{}) {
	_ = json.Unmarshal(this.Body(), &m)
	return
}

//func (this Response) BodyValue() convs.Value {
//	return convs.NewValue(this.BodyString())
//}

func (this Response) Header() http.Header {
	return this.header
}

func (this Response) Headers() []string {
	return this.headers
}

func (this Response) Code() int {
	return this.code
}

func (this Response) Err() error {
	return this.err
}

func (this Response) Error() string {
	if this.err != nil {
		return this.err.Error()
	}
	return ""
}

